<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>拍照</title>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            padding: 0;
            margin: 0;
        }

        .camera-wrap {
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            padding: 10px;
            box-sizing: border-box;
            position: relative;
        }

        .wrap-video {
            flex: 1;
            height: 0;
            display: flex;
        }

        .video-camera {
            flex: 1;
            width: 0;
        }

        video {
            width: 100%;
            height: 100%;
            margin: auto;
            background-color: black;
            display: block;
        }

        .video-pics {
            width: 210px;
        }

        .video-pics>div {
            margin-bottom: 10px;
            text-align: center;
        }

        .video-pics>div>label>img {
            cursor: pointer;
        }

        .wrap-btns {
            height: 50px;
            padding: 10px 0;
            box-sizing: border-box;
        }

        .wrap-btns button {
            padding: 5px 10px;
            border-radius: 2px;
            border: 1px solid #d9d9d9;
            color: #1a1a1a;
            margin-right: 10px;
            background-color: #fff;
            cursor: pointer;
        }

        .wrap-btns button:hover {
            background-color: rgba(4, 137, 151, 0.13);
        }

        .wrap-mask {
            font-size: 30px;
            font-weight: 600;
            text-align: center;
            padding-top: 42%;
            color: #fff;
            background-color: rgba(0, 0, 0, 0.3);
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            z-index: 999;
            display: none;
        }
    </style>
</head>

<body>
<div class="camera-wrap">
    <div class="wrap-video">
        <div class="video-camera">
            <video id="video"></video></td>
        </div>
        <div class="video-pics" id="output"></div>
    </div>
    <div class="wrap-btns">
        <button id="camera"></button>
        <button id="photo"></button>
        <button id="uploadImage"></button>
        <button id="deletePic"></button>
    </div>
    <div class="wrap-mask" id="wrapMask"></div>
</div>

<script type="text/javascript" src="jquery.js"></script>
<script>
    var localLang = window.localStorage.locale
    localLang = localLang ? localLang.toLocaleLowerCase() : 'zh-cn';
    $(document).ready(function () {
        // 国际化功能判断按钮名称
        if (localLang == 'zh-cn') {
            document.getElementById('camera').innerHTML = '选择摄像头'
            document.getElementById('photo').innerHTML = '拍摄照片'
            document.getElementById('uploadImage').innerHTML = '确认上传'
            document.getElementById('deletePic').innerHTML = '删除照片'
            document.getElementById('wrapMask').innerHTML = '上传中，请稍后~~~'
            return
        }
        if (localLang == 'en-us') {
            document.getElementById('camera').innerHTML = 'Switch camera'
            document.getElementById('photo').innerHTML = 'Photograph'
            document.getElementById('uploadImage').innerHTML = 'Upload'
            document.getElementById('deletePic').innerHTML = 'Delete'
            document.getElementById('wrapMask').innerHTML = 'Upload, please wait ~~~'
            return
        }
        if (localLang == 'zh-tw') {
            document.getElementById('camera').innerHTML = '選擇攝像頭'
            document.getElementById('photo').innerHTML = '拍攝照片'
            document.getElementById('uploadImage').innerHTML = '確認上傳'
            document.getElementById('deletePic').innerHTML = '刪除照片'
            document.getElementById('wrapMask').innerHTML = '上傳中，請稍後~~'
            return
        }
        getImgPicDom()
    });
    var video = document.getElementById('video');
    var output = document.getElementById("output");

    //访问用户媒体设备的兼容方法
    function getUserMedia(constraints) {
        if (navigator.mediaDevices.getUserMedia) {
            //最新的标准API
            navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
        } else if (navigator.webkitGetUserMedia) {
            //webkit核心浏览器
            navigator.webkitGetUserMedia(constraints, success, error);
        } else if (navigator.mozGetUserMedia) {
            //firfox浏览器
            navigator.mozGetUserMedia(constraints, success, error);
        } else if (navigator.getUserMedia) {
            //旧版API
            navigator.getUserMedia(constraints, success, error);
        }
    }

    function success(stream) {
        //兼容webkit核心浏览器
        // let CompatibleURL = window.URL || window.webkitURL;

        //将视频流设置为video元素的源
        console.log(stream);

        //video.src = CompatibleURL.createObjectURL(stream);
        video.srcObject = stream;
        video.play();
    }

    function error(error) {
        console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
    }

    //设备摄像头数据获取
    var device_videos = [];
    var device_videos_index = 0;
    navigator.mediaDevices.enumerateDevices().then(function (devices) {
        devices.forEach(function (dv) {
            var kind = dv.kind;
            if (kind.match(/^video.*/)) {
                device_videos.push(dv.deviceId);
            }
        });
    });

    getUserMedia({ video: { width: 1280, height: 720, deviceId: device_videos[0] } });

    document.getElementById('camera').addEventListener('click', function () {
        if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
            //调用用户媒体设备, 访问摄像头
            close();
            getUserMedia({ video: { width: 1280, height: 720, deviceId: device_videos[device_videos_index++ % device_videos.length] } });
        } else {
            if (localLang == 'zh-cn') {
                window.alert('不支持访问用户媒体');
                return
            }
            if (localLang == 'en-us') {
                window.alert('Access to the user media is not supported');
                return
            }
            if (localLang == 'zh-tw') {
                window.alert('不支持訪問用戶媒體');
                return
            }
        }
    })

    function close() { //关闭摄像头数据流
        if (video.srcObject) {
            try {
                var tracks = video.srcObject.getTracks();
                for (var track of tracks) {
                    track.stop();
                }
            } catch (e) {
                window.alert(e);
            }
        }
    }

    function getQueryString(name) {     //name为传入参数
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    var i = 0;

    document.getElementById("photo").addEventListener("click", function () {
        var canvas = document.createElement("canvas");
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
        i++;
        var imgUrl = canvas.toDataURL("image/png")
        // 20230831改为多选框
        var innerDoms = `<div id="imgWrap${i}" onclick="selectPic(\'${i}\')">
                                 <input type="checkbox" name="picCheckbox" value="${i}" id="checkbox${i}" onclick="selectPic(\'${i}\')" />
                                 <label for="${i}">
                                    <img title="双击照片可预览" id="imgPic${i}" width="160" height="90" src="${imgUrl}" ondblclick="previewPic(\'${imgUrl}\')" />
                                 </label>
                             </div>`
        output.innerHTML += innerDoms;
    });

    // 点击勾选
    function selectPic(index) {
        var checkboxStatus = document.getElementById('checkbox' + index).checked
        document.getElementById('checkbox' + index).checked = !checkboxStatus
    };

    // 预览照片
    function previewPic(src) {
        if (!src) {
            if (localLang == 'zh-cn') {
                window.alert('图片地址有误，无法预览');
                return
            }
            if (localLang == 'en-us') {
                window.alert('The image address is wrong, and cannot be preview');
                return
            }
            if (localLang == 'zh-tw') {
                window.alert('圖片地址有誤，無法預覽');
                return
            }
            return
        }
        const img = new window.Image();
        img.src = src;
        var newWin = window.open('');
        newWin.document.body.style.background = '#000';
        newWin.document.body.style.textAlign = 'center';
        newWin.document.body.appendChild(img);
        newWin.document.title = '图片预览';
        newWin.document.close();
    }

    // 上传按钮
    document.getElementById("uploadImage").onclick = function () {
        var checkedVal = getCheckedImgInfo('values')
        if (checkedVal.length < 1) {
            if (localLang == 'zh-cn') {
                window.alert('请至少选择一张照片');
                return
            }
            if (localLang == 'en-us') {
                window.alert('Please select at least one photo');
                return
            }
            if (localLang == 'zh-tw') {
                window.alert('請至少選擇壹張照片');
                return
            }
            return
        }
        $('#wrapMask').show()
        setTimeout(function () {
            // for (var j = 0; j < checkedVal.length; j++) {
            //     var base64Url = document.getElementById('imgPic' + checkedVal[j]).src.slice(22)
            //     if (!base64Url) {
            //         continue
            //     } else {
            //         uploadPicAjax(base64Url, checkedVal[j])
            //     }
            // }
            // var tempArr = []
            for (var j = 0; j < checkedVal.length; j++) {
                let imgPic = document.getElementById('imgPic' + checkedVal[j]).src.slice(22)
                // tempArr.push(imgPic)
                uploadPicAjax(imgPic, j)
            }
            // var base64Params = tempArr.join(',');
            // uploadPicAjax(base64Params, 0)
            $('#wrapMask').hide()
            window.alert('succes');
        }, 500)
    };

    // 上传调接口
    function uploadPicAjax(imgBase, index) {
        var ids = getQueryString('ids');
        var businessCode = getQueryString('businessCode');
        var bizCategory = getQueryString('bizCategory');
        // var ids = '1199049921675072'; //待删
        // var businessCode = 'T_LIMS_SAMPLE'; //待删
        // var bizCategory = 'receive'; //待删
        // var hostUrl = 'http://172.16.156.41:8081' //待删
        $.ajax({
            // url: hostUrl + "/open/post/" + businessCode + "/file",
            url: "/open/post/" + businessCode + "/file",
            type: "post",
            data: {
                "base64": imgBase,
                "ids": ids,
                "bizCategory": bizCategory
            },
            async: false,//异步请求
            success: function (res) {
                // document.getElementById('imgWrap' + index).remove()
                console.log('上传成功')
            },
            error: function (err) {
                console.log('上传失败')
            }
        });
    }

    // 删除按钮
    document.getElementById('deletePic').onclick = function () {
        var checkedVal = getCheckedImgInfo('values')
        if (checkedVal.length < 1) {
            if (localLang == 'zh-cn') {
                window.alert('请至少选择一张照片');
                return
            }
            if (localLang == 'en-us') {
                window.alert('Please select at least one photo');
                return
            }
            if (localLang == 'zh-tw') {
                window.alert('請至少選擇壹張照片');
                return
            }
            return
        }
        for (var j = 0; j < checkedVal.length; j++) {
            document.getElementById('imgWrap' + checkedVal[j]).remove()
        }
    };

    // 复选照片获取id及value
    function getCheckedImgInfo() {
        var tempIds = []
        var elements = $('input[name="picCheckbox"]')
        for (var m = 0; m < elements.length; m++) {
            if (elements[m].checked) {
                tempIds.push(elements[m].value)
            }
        }
        return tempIds
    }
</script>
</body>

</html>